package com.zuikaku.tool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

public class JDBCPool {
    private static String URL;
    private static String db_user;
    private static String db_password;

    private static List<Connection> jdbcConnectionList;

    private static int connCount =10;
    static {
        ResourceBundle rb = ResourceBundle.getBundle("dbconfig");
        URL = rb.getString("db.url");
        db_user = rb.getString("db.user");
        db_password = rb.getString("db.password");
        jdbcConnectionList = new ArrayList<>();
        for(int i=1;i<=10;i++){
            Connection connection = createConnection();
            if(connection!=null)
                jdbcConnectionList.add(connection);


        }
    }

    public static Connection getConnection(){
        if(jdbcConnectionList.size()>0){
            Connection conn = jdbcConnectionList.get(0);
            jdbcConnectionList.remove(conn);
            return conn;
        }else{
            return createConnection();
        }

    }

    public static void releaseConnection(Connection conn){
        jdbcConnectionList.add(conn);
    }

    public static void closeAllConnection(){
        jdbcConnectionList.forEach(p->{
            try {
                p.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        });
    }


    private static Connection createConnection(){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection(URL,db_user,db_password);
            return conn;
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }catch (SQLException e){
            e.printStackTrace();
        }
        return null;
    }
}
